/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/sort-comp */
/* eslint-disable react/jsx-no-bind */
/* eslint-disable no-shadow */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Button, message, Row, Col, Table, Modal, Radio } from 'antd';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import InfoCheck from '@/components/InfoCheck';
import Exception from '@/components/Exception';
import DispatchPianqu from '@/components/_pages/Post/Area/DispatchPianqu';
import { getLStorage } from '@/utils/utils';
import ScanConfiguration from './components/ScanConfiguration';
import GpAuthSetting from './components/GpAuthSetting';
import styles from './style.less';

const RadioGroup = Radio.Group;

@connect(({ allocation, loading, setting, user }) => ({
  allocation,
  userInfo: user.currentUser.user_info,
  userType: setting.options.key,
  topAccountTitle: setting.options.topAccountTitle,
  getPostList: loading.effects['allocation/getPostList'],
  deleteOption: loading.effects['allocation/deleteOption'],
  openService: loading.effects['allocation/openService'],
  getCode: loading.effects['allocation/getCode'],
  deductionLoading: loading.effects['allocation/deduction'],
  ...setting,
}))
@Form.create()
export default class PostOption extends PureComponent {
  constructor(props) {
    super(props);
    const { phone } = this.props.userInfo || {};
    this.state = {
      isShowDetail: false,
      record: {},
      selectedRowKeys: [],
      visible: false,
      authSettingVisible: false,
      area_id: getLStorage(`KB_GP_AREA_${phone}`),
    };
  }

  getDeductionInfo() {
    const { dispatch } = this.props;
    dispatch({
      type: 'allocation/getUserInfo',
    });
  }

  handleModalOk = () => {
    const { form, dispatch } = this.props;
    form.validateFields((err, values) => {
      if (err) return;
      dispatch({
        type: 'allocation/deduction',
        payload: {
          ...values,
        },
      }).then(() => {
        this.getDeductionInfo();
        this.triggerModal(false);
      });
    });
  };

  triggerModal = visible => {
    this.setState({
      visible,
    });
  };

  handleInfoReady(data) {
    if (!data.name) return;
    const { dispatch, userInfo = {} } = this.props;
    const { gp_area_ids = [], user_type, area_ids } = userInfo;
    const isCompany = area_ids == '*';
    const payload = {};
    if (user_type == 1) {
      const { area_id } = this.state;
      const reqAreaId = gp_area_ids.includes(area_id) ? area_id : isCompany ? '0' : gp_area_ids[0];
      payload.area_id = reqAreaId;
      this.setState({
        area_id: reqAreaId,
      });
    }
    dispatch({
      type: 'allocation/getPostList',
      payload,
    });
    this.getDeductionInfo();
  }

  // 开启/关闭服务
  openService({ disabled, id, scan_type, is_batch }) {
    const { dispatch } = this.props;
    const { area_id } = this.state;
    dispatch({
      type: 'allocation/openService',
      payload: {
        id,
        scan_type,
        is_batch,
        disabled,
        area_id,
      },
    });
  }

  showDetail(show, record) {
    this.setState({
      isShowDetail: show,
      record,
    });
  }

  // 批量开启关闭
  handleOpen(open) {
    const { selectedRowKeys } = this.state;
    const { dispatch } = this.props;
    const hasChoose = selectedRowKeys.length > 0;
    const id = selectedRowKeys.join(',');
    if (!hasChoose) {
      message.error(`请选择需要${open ? '开启' : '关闭'}的配置`, 1);
      return;
    }
    dispatch({
      type: 'allocation/openService',
      payload: {
        id,
        is_batch: 2,
        disabled: open ? '1' : '0', // 0关闭，1开启
      },
    })
      .then(() => {
        this.setState({ selectedRowKeys: [] });
      })
      .catch(() => {
        this.setState({ selectedRowKeys: [] });
      });
  }

  handleAuthSet = record => {
    this.setState({
      record,
      authSettingVisible: true,
    });
  };

  onChangePianqu = area_id => {
    const { dispatch } = this.props;
    this.setState(
      {
        area_id,
      },
      () => {
        dispatch({
          type: 'allocation/getPostList',
          payload: {
            area_id,
          },
        });
      },
    );
  };

  render() {
    const {
      isShowDetail,
      record = {},
      selectedRowKeys,
      visible,
      authSettingVisible,
      area_id,
    } = this.state;
    const {
      allocation,
      getPostList,
      form,
      deductionLoading,
      userType,
      topAccountTitle,
      userInfo = {},
    } = this.props;
    const { disabled, brand_name, scan_type, id } = record;
    const { postList, deductionInfo } = allocation;
    const { is_free, money, deduction_type, is_gp } = deductionInfo;
    const isZyAccount = userType === 'post' || userType === 'yjy';

    if (is_gp == 0 && isZyAccount) {
      // 当县级网点无共配权限时，提示
      return (
        <Exception
          type="403"
          title={`您所在的网点尚未开通共配服务，请联系${topAccountTitle}开通！`}
        />
      );
    }

    const feeType = is_free == '1' ? '免费试用' : is_free == '2' ? '后付费' : '预付费';

    if (!postList) return null;
    const columns = [
      {
        title: '品牌',
        dataIndex: 'brand',
        key: 'brand',
        align: 'center',
      },
      {
        title: '网点编号',
        dataIndex: 'branch_code',
        key: 'branch_code',
        align: 'center',
      },
      {
        title: '网点名称',
        dataIndex: 'branch_name',
        key: 'branch_name',
        align: 'center',
      },
      {
        title: '共配权限',
        dataIndex: 'status',
        key: 'status',
        align: 'center',
        render: (text, record) => (
          <>
            <span style={{ marginRight: 20 }}>{record.disabled == '1' ? '已开启' : '已关闭'}</span>
            <Button onClick={() => this.handleAuthSet(record)} type="primary" size="small">
              权限控制
            </Button>
          </>
        ),
      },
      {
        title: '扫描配置',
        align: 'center',
        render: record => (
          <div className={styles.control}>
            <Button type="primary" size="small" onClick={this.showDetail.bind(this, true, record)}>
              扫描配置
            </Button>
          </div>
        ),
      },
    ];

    const rowSelection = {
      selectedRowKeys,
      onChange: selectedRowKeys => {
        this.setState({
          selectedRowKeys,
        });
      },
    };

    const moneyForShow = money || '0';
    // 公司片区层级
    const companyArea = userType == 'yz' && userInfo.area_ids == '*';

    return !isShowDetail ? (
      <PageHeaderLayout
        title={
          <Row type="flex" justify="space-between" align="middle">
            <Col>巴枪扫描配置</Col>
            <Col>
              <Row type="flex" align="middle">
                {/* 驿加易不需要显示 */}
                {(userType == 'post' || companyArea) && (
                  <Col style={{ fontSize: 16 }}>
                    {`您当前的共配费用：${moneyForShow}/票（${feeType}）`}
                  </Col>
                )}
                {!isZyAccount &&
                  companyArea && (
                    <Col>
                      <Button type="primary" onClick={() => this.triggerModal(true)}>
                        扣费设置
                      </Button>
                    </Col>
                  )}
              </Row>
              <Row>
                <Col>
                  <DispatchPianqu type="gp" onChange={this.onChangePianqu} />
                </Col>
              </Row>
            </Col>
          </Row>
        }
      >
        <InfoCheck onReady={this.handleInfoReady.bind(this)} />
        <div className={styles.main}>
          <div className={styles.PostOption}>
            <Table
              className={styles.Tables}
              dataSource={postList}
              columns={columns}
              rowKey="id"
              pagination={false}
              rowSelection={rowSelection}
              loading={getPostList}
            />
          </div>
          <Row type="flex" gutter={[20, 20]} style={{ margin: 0 }}>
            <Col>
              <a onClick={this.handleOpen.bind(this, true)}>批量开启权限</a>
            </Col>
            <Col>
              <a onClick={this.handleOpen.bind(this, false)}>批量关闭权限</a>
            </Col>
          </Row>
        </div>
        <GpAuthSetting
          visible={authSettingVisible}
          onClose={() => this.setState({ authSettingVisible: false })}
          onSubmit={values => this.openService(values)}
          open={disabled}
          brand={brand_name}
          checkedAuth={scan_type}
          id={id}
          area_id={area_id}
        />
        <Modal
          title="扣费设置"
          visible={visible}
          onCancel={() => this.triggerModal(false)}
          onOk={this.handleModalOk}
          confirmLoading={deductionLoading}
        >
          <Form>
            <Form.Item>
              {form.getFieldDecorator('type', {
                initialValue: deduction_type,
              })(
                <RadioGroup>
                  <Radio key="xlw" value="1">
                    快宝智慧快递管理平台扣费
                  </Radio>
                  <Radio key="account" value="2">
                    快递员账户扣费
                  </Radio>
                </RadioGroup>,
              )}
            </Form.Item>
          </Form>
        </Modal>
      </PageHeaderLayout>
    ) : (
      <ScanConfiguration showDetail={this.showDetail.bind(this)} setRecord={record} />
    );
  }
}
